<?php

namespace frontend\controllers;

use Yii;
use common\models\Subject;
use common\models\Post;
use yii\data\Pagination;
use yii\web\Controller;
use common\components\SubjectHelper;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * SubjectController implements the CRUD actions for Subject model.
 */
class SubjectController extends Controller {

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
            // index页面缓存，1天有效
            'indexCache' => [
                'class' => 'common\components\PageCache',
                'only' => ['index'],
                'duration' => 0,
                'variations' => [\Yii::$app->language,],
                'dependency' => [
                    'class' => 'yii\caching\DbDependency',
                    'sql' => 'SELECT `id` FROM `post` ORDER BY `id` DESC LIMIT 1',
                ],
            ],
            // view页面缓存，1天有效
            'viewCache' => [
                'class' => 'common\components\PageCache',
                'only' => ['view'],
                'duration' => 0,
                'variations' => [\Yii::$app->language,],
                'dependency' => [
                    'class' => 'yii\caching\DbDependency',
                    'sql' => 'SELECT `id` FROM `post` where cid="'.\Yii::$app->request->get('id').'" ORDER BY `id` DESC LIMIT 1',
                ],
            ],
            // list页面缓存，1天有效
            'listCache' => [
                'class' => 'common\components\PageCache',
                'only' => ['list'],
                'duration' => 0,
                'variations' => [\Yii::$app->language,],
                'dependency' => [
                    'class' => 'yii\caching\DbDependency',
                    'sql' => 'SELECT count(*) FROM `subject`',
                ],
            ],
            // Http缓存
            'HttpCache' => [
                'class' => 'yii\filters\HttpCache',
                'only' => ['index'],
                'etagSeed' => function ($action, $params) {
                    $post = Post::find()->select(['id'])->orderBy('id desc')->limit(1)->asArray()->one();
                    return serialize([$post]);
                },
            ],            
            // Http缓存
            'HttpCache' => [
                'class' => 'yii\filters\HttpCache',
                'only' => ['view'],
                'etagSeed' => function ($action, $params) {
                    $post = Post::find()->select(['id'])->where(['cid' => \Yii::$app->request->get('id')])->orderBy('id desc')->limit(1)->asArray()->one();
                    return serialize([$post]);
                },
            ],            
        ];
    }

    /**
     * Lists all Subject models.
     * @return mixed
     */
    public function actionIndex() {
        $query = Post::find()->with('c')->where(['enable' => 1])->asArray();
        $pagination = new Pagination([
            'defaultPageSize' => 20,
            'totalCount' => $query->count(),
        ]);
        $model = $query->orderBy('id desc')
                ->offset($pagination->offset)
                ->limit($pagination->limit)
                ->all();

        $hot = Post::find()->with('c')->asArray()->orderBy('view desc')->limit(10)->all();
        $cache = Yii::$app->cache;
        $tag = $cache->get("tagPost");
        if ($tag === false) {
            $tag = SubjectHelper::PostTags();
            $cache->set("tagPost", $tag);
        }
        return $this->render('index', [
                    'model' => $model,
                    'hot' => $hot,
                    'tag' => $tag,
                    'pagination' => $pagination,
        ]);
    }

    /**
     * Displays a single Subject model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id) {
        $subject = Subject::find()->select(['id', 'title'])->where(['id' => $id])->asArray()->one();
        if (!empty($subject)) {
            $query = Post::find()->where(['cid' => $subject['id']])->andWhere(['enable' => 1])->asArray();
            $pagination = new Pagination([
                'defaultPageSize' => 20,
                'totalCount' => $query->count(),
            ]);
            $model = $query->orderBy('id desc')
                    ->offset($pagination->offset)
                    ->limit($pagination->limit)
                    ->all();
            $hot = Post::find()->with('c')->andWhere(['enable' => 1])->asArray()->orderBy('view desc')->limit(10)->all();
            $cache = Yii::$app->cache;
            $tag = $cache->get("tagPost");
            if ($tag === false) {
                $tag = SubjectHelper::PostTags();
                $cache->set("tagPost", $tag);
            }
            return $this->render('view', [
                        'model' => $model,
                        'subject' => $subject,
                        'hot' => $hot,
                        'tag' => $tag,
                        'pagination' => $pagination,
            ]);
//            var_dump($model);
        } else {
            throw new NotFoundHttpException(Yii::t('common', 'NotFound'));
        }
    }

    // 主题列表页
    public function actionList() {
        $cache = Yii::$app->cache;
        $model = $cache->get("subjectIndex");
        if ($model === false) {
            $model = Subject::find()->select(['id','title','desc','img'])->asArray()->all();
            $cache->set("subjectIndex", $model);
        }
        $hot = Post::find()->orderBy('view desc')->limit(20)->asArray()->all();
        return $this->render('list', [
            'model' => $model,
            'hot' => $hot,
        ]);
    }

    /**
     * Finds the Subject model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Subject the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id) {
        if (($model = Subject::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

}
